package com.demo2do.fms.admin.web.controller.data.business;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.fms.admin.entity.report.ExportType;
import com.demo2do.fms.admin.entity.report.data.FacilityDistanceReportSearch;
import com.demo2do.fms.admin.entity.search.data.FacilityDistanceSearch;
import com.demo2do.fms.admin.service.data.FacilityDistanceService;
import com.demo2do.fms.admin.utils.FormatUtils;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.admin.web.view.ExcelTemplateView;
import com.demo2do.fms.entity.authority.Organization;
import com.demo2do.fms.entity.data.business.FacilityDistance;
import com.demo2do.fms.entity.data.business.LoadPlace;

/**
 * 行驶公里数管理
 * 
 * @author Ysy
 */
@Controller
@RequestMapping("/facility-distances")
@MenuSetting("menu-data")
public class FacilityDistanceController {
    
    public static final Logger logger = LoggerFactory.getLogger(FacilityDistanceController.class);
    
    @Autowired
    @Qualifier("facilityDistanceService")
    private FacilityDistanceService facilityDistanceService;
    
    /**
     * 
     * @param orgIds
     * @param page
     * @return
     */
    @MenuSetting("submenu-facility-distance")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView list(@Secure(property = "orgIds") List<Long> orgIds, Page page){
       
        ModelAndView modelAndView = new ModelAndView("data/business/facility-distance/facility-distance-list");
        
        int totals = facilityDistanceService.count(orgIds);
        if(totals > 0) {
            
            List<FacilityDistance> facilityDistances = facilityDistanceService.list(orgIds, page.with(totals));
         
            modelAndView.addObject("page", page);
            modelAndView.addObject("facilityDistances", facilityDistances);
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param orgIds
     * @return
     */
    @MenuSetting("submenu-facility-distance")
    @RequestMapping(value = "search", method = RequestMethod.GET)
    public ModelAndView search(@Secure(property = "orgIds") List<Long> orgIds){
        
        ModelAndView modelAndView = new ModelAndView("data/business/facility-distance/facility-distance-search");
        
        modelAndView.addObject("orgIds", orgIds);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param facilityDistanceSearch
     * @param page
     * @param request
     * @return
     */
    @MenuSetting("submenu-facility-distance")
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    public ModelAndView onSearch(FacilityDistanceSearch facilityDistanceSearch, Page page, HttpServletRequest request){
        
        ModelAndView modelAndView = new ModelAndView("data/business/facility-distance/facility-distance-list");
        
        int totals = facilityDistanceService.count(FacilityDistance.class, facilityDistanceSearch.getFilter());
        
        if(totals > 0){
            
            List<FacilityDistance> facilityDistances = facilityDistanceService.search(FacilityDistance.class, facilityDistanceSearch, page.with(totals));
            
            modelAndView.addObject("facilityDistances", facilityDistances);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter","page"));
        
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param orgIds
     * @return
     */
    @MenuSetting("submenu-facility-distance")
    @RequestMapping(value = "/prepare", method = RequestMethod.GET)
    public ModelAndView prepare(@Secure(property = "orgIds") List<Long> orgIds){
        
        ModelAndView modelAndView = new ModelAndView("data/business/facility-distance/facility-distance-prepare");

        modelAndView.addObject("orgIds", orgIds);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param orgIds
     * @param organization
     * @param fromLoadPlace
     * @param toLoadPlace
     * @return
     */
    @MenuSetting("submenu-facility-distance")
    @RequestMapping(value = "", method = RequestMethod.GET, params = "prepare")
    public ModelAndView onPrepare(@Secure(property = "orgIds") List<Long> orgIds,
                                  @Preloading("orgId") Organization organization, 
                                  @Preloading(value = "fromLoadPlaceId", name = "fromLoadPlace") LoadPlace fromLoadPlace,
                                  @Preloading(value = "toLoadPlaceId", name = "toLoadPlace") LoadPlace toLoadPlace) {
        
        ModelAndView modelAndView = new ModelAndView("data/business/facility-distance/facility-distance-prepare");
        
        List<FacilityDistance> facilityDistances = facilityDistanceService.list(organization, fromLoadPlace, toLoadPlace);
        
        modelAndView.addObject("facilityDistances", facilityDistances);
        modelAndView.addObject("orgIds", orgIds);
        modelAndView.addObject("organization", organization);
        modelAndView.addObject("fromLoadPlace", fromLoadPlace);
        modelAndView.addObject("toLoadPlace", toLoadPlace);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param orgId
     * @param fromLoadPlaceId
     * @param toLoadPlaceId
     * @return
     */
    @MenuSetting("submenu-facility-distance")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create(@RequestParam("organization") Long orgId, 
                               @RequestParam("fromLoadPlace") Long fromLoadPlaceId,
                               @RequestParam("toLoadPlace") Long toLoadPlaceId){
        
        ModelAndView modelAndView = new ModelAndView("data/business/facility-distance/facility-distance-create");
        
        modelAndView.addObject("orgId", orgId);
        modelAndView.addObject("fromLoadPlaceId", fromLoadPlaceId);
        modelAndView.addObject("toLoadPlaceId", toLoadPlaceId);
        
        return modelAndView;
    }
    
    /**
     * 新建派车单 - 准备
     * 
     * @param operator
     * @param facilityDistance
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onCreate(@Secure(property = "id") Long operator,
                                             FacilityDistance facilityDistance) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            facilityDistanceService.create(facilityDistance, operator);
            
        } catch (Exception e) {
            
            logger.info("#onCreate fail, exception is [{}]", e);
            
            httpResult.fail("500").message(e.getMessage());
            
            return httpResult;
        }
        
        httpResult.success().message("新增成功");
        
        return httpResult;
    }

    /**
     * 
     * @param id
     * @return
     */
    @MenuSetting("submenu-facility-distance")
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id){
        
        ModelAndView modelAndView = new ModelAndView("data/business/facility-distance/facility-distance-edit");
        
        FacilityDistance facilityDistance = facilityDistanceService.load(FacilityDistance.class, id);
        
        modelAndView.addObject("facilityDistance", facilityDistance);
        
        return modelAndView;
    }
    
    /**
     * 
     * 
     * @param operator
     * @param facilityDistance
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEdit(@Secure(property = "id") Long operator, 
                                           @Preloading("facilityDistanceId") FacilityDistance facilityDistance){
        
        HttpResult httpResult = new HttpResult();
        
        facilityDistanceService.edit(operator, facilityDistance);
        
        httpResult.success().message("设置成功");
        
        return httpResult;
        
    }

    /**
     * 输出当前页记录
     * 
     * @param search
     * @param orgIds
     * @param page
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView export(FacilityDistanceSearch search,
                               @Secure(property = "orgIds") List<Long> orgIds, Page page) {
        
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("data/business/facility-distance-export.xlsx"));
        
        // 1. list result
        if (CollectionUtils.isEmpty(search.getOrganizationIds())) {
            search.setOrganizationIds(orgIds);
        }
        int totals = facilityDistanceService.count(FacilityDistance.class, search.getFilter());
        if(totals > 0){
            List<FacilityDistance> facilityDistances = facilityDistanceService.search(FacilityDistance.class, search, page.with(totals));
            modelAndView.addObject("facilityDistances", facilityDistances);
        }
        
        // 2. attribute
        modelAndView.addObject("type", ExportType.CURRENT);
        
        // 3. format util
        FormatUtils fmt = new FormatUtils();
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
        
    }
    
    /**
     * 输出所有记录
     * 
     * @param search
     * @param orgIds
     * @return
     */
    @RequestMapping(value = "/export-all", method = RequestMethod.GET)
    public ModelAndView exportAll(FacilityDistanceReportSearch search, @Secure(property = "orgIds") List<Long> orgIds) {
        
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("data/business/facility-distance-export.xlsx"));
        
        // 1. list result 
        if (CollectionUtils.isEmpty(search.getOrganizationIds())) {
            search.setOrganizationIds(orgIds);
        }
        List<Map<String, Object>> results = facilityDistanceService.exportAll(search);
        modelAndView.addObject("results", results);
        
        // 2. attribute
        modelAndView.addObject("type", ExportType.ALL);
        
        // 3. format util
        FormatUtils fmt = new FormatUtils();
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
        
    }
}

